<template>
  <div>
    <Row>
      <Card>
        <Form ref="search" :model="searchData" :label-width="120">
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="测评用户类型" prop="userType">
                <Input
                  v-model="searchData.userType"
                  suffix="ios-search"
                  placeholder="请输入测评用户类型"
                  style="width: 250px;"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>
              </FormItem>
            </i-col>
          </Row>
          <FormItem>
            <Button
              v-if="btnAccess.query"
              type="primary"
              style="marigin:0 20px"
              :loading="searchLoading"
              @click="searchSubmit(10,1)"
            >提交搜索</Button>
            <Button @click="submitReset">重置搜索</Button>
          </FormItem>
        </Form>
      </Card>
    </Row>
    <Row style="margin-top:20px">
      <Card>
        <div class="btn-arrs">
          <Button type="info" v-if="btnAccess.add" @click="showModal">添加测评用户类型</Button>
        </div>
        <Table border :loading="tabelLoading" :columns="userHead" :data="userData"></Table>
        <div style="margin-top:20px;margin-left:35%">
          <Page
            @on-change="pageNumberChange"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
          />
        </div>
      </Card>
    </Row>
    <!-- 添加测评用户类型/编辑测评用户类型 -->
    <Modal
      v-model="isUserModal"
      :title="userModalTitle"
      :loading="userModalLoading"
      @on-cancel="cancelUserModal"
    >
      <Form ref="userManagement" :model="userForm" :rules="userReg" :label-width="120">
        <Row>
          <Col span="11">
            <FormItem label="测评用户类型" prop="userType">
              <Input v-model="userForm.userType" placeholder="请输入测评用户类型" style="width:250px;"></Input>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button
          type="primary"
          v-if="btnAccess.upd"
          size="large"
          :loading="userModalLoading"
          @click="submitUserModal"
        >提交</Button>
        <Button size="large" @click="cancelUserModal">取消</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { hasOneOf } from "@/libs/tools";
import { roleMangeAjax } from "@/api/systemMange";
const TYPE_URL = "/exam/User/userTypeManage";
// 删除URL
const DELETE_URL = "/userRole/delete";
// 修改URL
const UPDATE_URL = "/userRole/update";
// 添加URL
const INSERT_URL = "/userRole/insert";
// 查询URL
const QUERY_URL = "/userRole/query";
// 手机验证
const PHONE_REG = new RegExp("^1(3|4|5|7|8)\\d{9}$");
const INSERT_TITLE = "添加测评用户类型";
const UPDATE_TITLE = "编辑测评用户类型";
export default {
  data() {
    return {
      // 增删改查权限按钮
      btnAccess: {
        add: true,
        add2: "inline-block",
        del: "inline-block",
        upd: true,
        query: true
      },
      searchData: { optionType: "query", userType: "" },
      isUserModal: false, // 模态框
      searchLoading: false, // 搜索Loading
      userModalLoading: false, // 提交loading
      tabelLoading: false, // 表格loading
      userModalTitle: "", // 模态框title
      isResponsible: "",
      pageSize: 10,
      pageNumber: 1,
      pageTotal: 10,
      userForm: {
        userType: "" // 测评用户类型
      },
      userReg: {
        userType: [
          {
            required: true,
            message: "请输入用户类型",
            trigger: "blur"
          }
        ]
      },
      userData: [],
      userHead: [
        {
          title: "测评用户类型名",
          key: "userType"
        },
        {
          title: "操作",
          key: "action",
          width: 250,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.userForm = JSON.parse(JSON.stringify(params.row));
                      console.log(this.userForm);
                      this.userModalTitle = "编辑测评用户类型";
                      this.isUserModal = true;
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error"
                  },
                  style: {
                    display: this.btnAccess.del
                  },
                  on: {
                    click: () => {
                      this.deleteUser(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ]
    };
  },
  methods: {
    // 搜索
    searchSubmit(pageSize, pageNumber) {
      this.searchLoading = true;
      this.searchData.optionType = "query";
      this._getData(this.searchData, TYPE_URL, this.pageSize, this.pageNumber);
    },
    // 重置搜索
    submitReset() {
      this.searchLoading = false;
      this.searchData = {
        userName: "",
        userDepartment: "",
        userPermissions: ""
      };
    },
    // 删除用户
    deleteUser(row) {
      if (this.accessAgent) {
        this.$Message.error("权限不足！");
        return;
      }
      this.$Modal.confirm({
        title: "删除用户",
        content: "<p>删除完成后将无法恢复</p>",
        loading: true,
        onOk: () => {
          let obj = { optionType: "del", id: row.id };
          this._addOrupdate(obj, TYPE_URL).then(result => {
            this.$Modal.remove();
            if (result.code === "200") {
              this.$Message.info("删除成功!");
              this.searchData.optionType = "query";
              this._getData(
                this.searchData,
                TYPE_URL,
                this.pageSize,
                this.pageNumber
              );
            } else {
              this.$Message.error(result.message);
            }
          });
        }
      });
    },
    // 显示模态框
    showModal() {
      // 获取菜单权限值
      this.userForm.haveRights = this.menArr;
      // 获取县级指标值
      this.userForm.indexRights = this.indexAllArr;
      this.userModalTitle = "添加测评用户类型";
      this.isUserModal = true;
      this.roleSelect = false;
    },
    // 提交
    submitUserModal() {
      this.$refs["userManagement"].validate(valid => {
        if (valid) {
          this.userModalLoading = true;
          if (this.userModalTitle === INSERT_TITLE) {
            this.userForm.optionType = "add";
            this._addOrupdate(this.userForm, TYPE_URL).then(result => {
              this.isUserModal = false;
              this.userModalLoading = false;
              console.log(result);
              if (result.code === "200") {
                this.$Message.success("添加成功！");
                this.searchData.optionType = "query";
                this._getData(
                  this.searchData,
                  TYPE_URL,
                  this.pageSize,
                  this.pageNumber
                );
              } else {
                this.$Message.error("添加失败！");
              }
            });
          } else if (this.userModalTitle === UPDATE_TITLE) {
            this.userForm.optionType = "update";
            this._addOrupdate(this.userForm, TYPE_URL).then(result => {
              this.isUserModal = false;
              this.userModalLoading = false;
              if (result.code === "200") {
                this.$Message.success("修改成功");
                this.searchData.optionType = "query";
                this._getData(
                  this.searchData,
                  TYPE_URL,
                  this.pageSize,
                  this.pageNumber
                );
              } else {
                this.$Message.error(result.message);
              }
            });
          }
        } else {
          this.$Message.error("请填写完整！");
        }
      });
    },
    cancelUserModal() {
      this.$refs["userManagement"].resetFields();
      this.userModalLoading = false;
      this.isUserModal = false;
      this.userForm = {
        userName: "" // 测评用户类型名
      };
    },
    // 页码
    pageNumberChange(pageNumber) {
      this.pageNumber = pageNumber;
      this._getData(this.searchData, QUERY_URL, this.pageSize, this.pageNumber);
    },
    // 页数
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this._getData(this.searchData, QUERY_URL, this.pageSize, this.pageNumber);
    },
    // 添加/修改
    _addOrupdate(formData, url) {
      const keyOne = "typeFilter";
      return new Promise((resolve, reject) => {
        roleMangeAjax({ formData, url, keyOne })
          .then(result => {
            if (result.data !== undefined) {
              resolve(result.data);
            } else {
              reject(err);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 查询
    _getData(formData, url, pageSize, pageNumber) {
      this.tabelLoading = true;
      formData = Object.assign(formData, {
        pageSize,
        pageNumber
      });
      const keyOne = "typeFilter";
      roleMangeAjax({ formData, url, keyOne })
        .then(result => {
          this.tabelLoading = false;
          if (result.data.code === "200") {
            this.searchLoading = false;
            this.userData = result.data.results.data;
            this.$Message.success("查询成功");
          } else {
            this.$Message.error("查询失败");
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  mounted() {},
  created() {
    // this.searchData.optionType = "query";
    this._getData(this.searchData, TYPE_URL);

    // 获取按钮权限
    let btnAccess = sessionStorage.getItem("btnaccess");
    this.globalFunction(btnAccess);
  },
  computed: {
    getDepartmentList() {
      return this.$store.state.user.departmentList;
    },
    getDepartment() {
      return this.$store.state.user.department;
    },
    access() {
      return this.$store.state.user.access;
    },
    // 管理员
    accessAdmin() {
      return hasOneOf(["admin"], this.access);
    },
    // 责任人
    accessRespons() {
      return hasOneOf(["responsible"], this.access);
    },
    // 经办人
    accessAgent() {
      return hasOneOf(["agent"], this.access);
    }
    //
  }
};
</script>
<style scoped>
.index-title {
  font-size: 14px;
  font-weight: bold;
}
</style>
